import datetime
import os
import struct
from pprint import pprint

# from mpl_finance import candlestick_ohlc, candlestick2_ohlc

#通达信目录
tdx_dir = "c:\\zd_zszq\\"
sh_dir = "vipdoc\\sh\\fzline"
sz_dir = "vipdoc\\sz\\fzline"
#通达信官网下载数据目录
download_dir = "../../market_data"


def get_tdx_stock_daydata(fileName, code):
    ofile = open(fileName, "rb")
    buf = ofile.read()
    ofile.close()
    num = len(buf)
    no = num / 32
    print("共有 %s 个数据块" % no)
    b = 0
    e = 32
    items = []
    for i in range(int(no)):
        a = struct.unpack("iiiiifii", buf[b:e])
        year = int(a[0] / 10000)
        m = int((a[0] % 10000) / 100)
        month = str(m)
        if m < 10:
            month = "0" + month
        d = (a[0] % 10000) % 100
        for j in range(8):
            print("a[%s]=%s" % (j, a[j]))
        day = str(d)
        if d < 10:
            day = "0" + str(d)
        dd = str(year) + "-" + month + "-" + day
        openPrice = a[1] / 100.0
        high = a[2] / 100.0
        low = a[3] / 100.0
        close = a[4] / 100.0
        amount = a[5] / 10.0
        vol = a[6]
        # unused = a[7]
        item = [code, dd, str(openPrice), str(high), str(low), str(close),
                str(amount), str(vol)]
        # print(item)
        items.append(item)
        b = b + 32
        e = e + 32
    print(len(items))
    print(items)
    return items


def get_tdx_stock_minutedata(fileName, code):
    """功能：读取通达信软件目录下的5分钟股票历史数据，返回数据列表.

    Args:
        fileName (string): 文件名全称，用来直接打开读取
        code (string): 合约名称，比如"000000"

    Return:
        data_list (list): 每个元素共7项内容：[合约名称, 日期时间, 开, 高, 低, 收,
                                              持仓量, 成交量]
    """
    data_list = []
    if os.path.isfile(fileName):
        ofile = open(fileName, "rb")
        buf = ofile.read()
        ofile.close()
        num = len(buf)
        no = num / 32
        print("文件 %s 共有 %s 个数据块" % (fileName, no))
        b = 0
        e = 32
        for i in range(int(no)):
            a = struct.unpack("hhfffffii", buf[b:e])
            year = a[0] // 2048 + 2004
            month = a[0] % 2048 // 100
            day = a[0] % 2048 % 100
            hour = a[1] // 60
            minute = a[1] % 60
            minute_str = str(minute) if minute >= 10 else "0" + str(minute)
            # print("y,m,d=%s, hour=%s, minute=%s" % (a[0], hour, minute))
            dt_str = "%s-%s-%s %s:%s" % (
                str(year), str(month), str(day), str(hour), minute_str)
            oprice = a[2]
            hprice = a[3]
            lprice = a[4]
            cprice = a[5]
            # 成交金额
            amount = a[6]
            # 成交量
            vol = a[7]
            # unused = a[7]
            item = [code, dt_str, oprice, hprice, lprice, cprice, amount, vol]
            # print(item)
            data_list.append(item)
            b = b + 32
            e = e + 32
        # pprint(data_list)
        # print('data_list长度为：%s' % len(data_list))
    else:
        print("5分钟行情文件 %s 不存在！" % (fileName))
    # print('准备return data_list.')
    return data_list


def get_tdx_stock_minutedata2(fileName, code):
    """功能：读取通达信官网下载的5分钟股票历史数据，返回数据列表.

    Args:
        fileName (string): 文件名全称，用来直接打开读取
        code (string): 合约名称，比如"000000"

    Return:
        data_list (list): 每个元素共7项内容：[合约名称, 日期时间, 开, 高, 低, 收,
                                              持仓量, 成交量]
    """
    data_list = []
    if os.path.isfile(fileName):
        ofile = open(fileName, "rb")
        buf = ofile.read()
        ofile.close()
        num = len(buf)
        no = num / 32
        print("文件 %s 共有 %s 个数据块" % (fileName, no))
        b = 0
        e = 32
        for i in range(int(no)):
            a = struct.unpack("hhiiiifii", buf[b:e])
            year = a[0] // 2048 + 2004
            month = a[0] % 2048 // 100
            day = a[0] % 2048 % 100
            hour = a[1] // 60
            minute = a[1] % 60
            minute_str = str(minute) if minute >= 10 else "0" + str(minute)
            # print("y,m,d=%s, hour=%s, minute=%s" % (a[0], hour, minute))
            dt_str = "%s-%s-%s %s:%s" % (
                str(year), str(month), str(day), str(hour), minute_str)
            oprice = a[2]
            hprice = a[3]
            lprice = a[4]
            cprice = a[5]
            amount = a[6]   # 持仓量
            vol = a[7]
            # unused = a[7]
            item = [code, dt_str, oprice, hprice, lprice, cprice, amount, vol]
            # print(item)
            data_list.append(item)
            b = b + 32
            e = e + 32
        pprint(len(data_list))
        pprint(data_list)
    else:
        print("5分钟行情文件 %s 不存在！" % (fileName))
    return data_list


def get_tdx_filename(stockid):
    if stockid[0] == '6':
        subdir = sh_dir
        mkt = 'sh'
    else:
        subdir = sz_dir
        mkt = 'sz'
    filename = '%s%s.lc5' % (mkt, stockid)
    tdx_filename = os.path.join(tdx_dir, subdir, filename)
    return tdx_filename


def log_file(log_str, stockid):
    str_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    log_filename = '%s.log' % stockid
    with open(log_filename, 'a', encoding='utf-8') as my_logfile:
        log_str = '%s %s' % (str_dt, log_str)
        my_logfile.write(log_str + '\n')


if __name__ == "__main__":
    stockid = "600581"
    full_tdx_filename = get_tdx_filename(stockid)
    # full_tdx_filename = os.path.join(tdx_dir, sh_dir, "sh600320.lc5")
    # full_tdx_filename = os.path.join(tdx_dir, sz_dir, "sz002194.lc5")
    # full_dl_filename = os.path.join(download_dir, "sh600320.5")
    # get_tdx_stock_minutedata(full_tdx_filename, "600320")
    hist_list = get_tdx_stock_minutedata(full_tdx_filename, stockid)
    for record in hist_list:
        log_file(record, stockid)
